import styles from './index.module.less';
import { getYuanGong, historyPositionFields } from '@/utils/helper';
import { useEffect, useRef, useState } from 'react';
import { ProTable, ProColumns } from '@ant-design/pro-components';
import {
  formatNum,
  getTimestamp,
  getUsdtNum,
  handleDirection,
  isLocal,
  isSuccess,
  jiaFa,
  setDefEmployeeId,
} from '@/utils';
import { historyPositionApi, userListApi } from '@/api';
import dayjs from 'dayjs';
import PositionType from './PositionType';
import { yuanGongLie } from './ComonOrder';
import { YSXYingKui } from './CommonCpn';

export default function HistoryPosition() {
  const [loading, setLoading] = useState(false);
  const tableRef: any = useRef('');
  const [yuanGongs, setYuanGongs] = useState<any>([]);
  const [defYuanGongId, setDefYuanGongId] = useState<any>('');
  const [zongYingKui, setZongYingKui] = useState<any>(0);
  useEffect(() => {
    initYuanGong();
  }, []);

  // 请求
  async function request(e: any) {
    const params: any = {
      ...e,
      userIds: [e.yuanGongId],
    };
    if (params?.side === 'all') delete params.side;
    if (params?.pnl === 'all') delete params.pnl;
    console.log('params: 历史仓位', params);
    setLoading(true);
    const res: any = await historyPositionApi(params);
    setLoading(false);
    console.log('res: 历史仓位1', res?.data, res?.data[0]);
    if (!isSuccess(res)) return { data: [], total: 0 };
    const list = res?.data;
    const _list = list.map((item: any) => item?.ysxYingKui?.pnl);
    console.log('_list: ', _list);
    const _zongYingKui = jiaFa(_list);
    console.log('_zongYingKui: ', _zongYingKui);
    setZongYingKui(_zongYingKui);
    return { data: list, total: res?.data?.total, success: true };
  }

  const columns: any[] = [
    yuanGongLie(yuanGongs, defYuanGongId, true),
    {
      title: '合约',
      dataIndex: 'contract',
      width: 150,
      hideInSearch: true,
      render: (text: any, record: any) => <PositionType record={record} showFangXiang={false} />,
    },
    {
      title: '方向',
      dataIndex: 'newSide',
      hideInSearch: true,
      render: (text: any, record: any) => (
        <div className={`${text === 'long' ? 'color-red' : 'color-green'}`}>
          {text === 'long' ? '做多' : '做空'}
        </div>
      ),
    },
    // {
    //   title: '状态',
    //   dataIndex: 'text',
    //   hideInSearch: true,
    //   render: (text: any, record: any) => <>{text.includes('liq-') ? '强制平仓' : '全部平仓'}</>,
    // },
    {
      title: '全部平仓时间',
      dataIndex: 'time',
      hideInSearch: true,
      width: 130,
      render: (text: any) => <>{dayjs(text * 1000).format('YYYY-MM-DD HH:mm:ss')}</>,
    },
    {
      title: '平仓时间',
      dataIndex: 'time',
      hideInTable: true,
      valueType: 'dateRange',
      search: {
        transform: (e: any) => ({
          from: getTimestamp(`${e[0]} 00:00:00`),
          to: getTimestamp(`${e[1]} 24:00:00`),
        }),
      },
      // initialValue: ['2025-02-01', '2025-03-19']
    },
    YSXYingKui(),
    {
      title: '开仓时间',
      dataIndex: 'first_open_time',
      hideInSearch: true,
      width: 100,
      render: (text: any) => <>{dayjs(text * 1000).format('YYYY-MM-DD HH:mm:ss')}</>,
    },
    {
      title: '开仓均价',
      dataIndex: 'kaiCangJunJia',
      hideInSearch: true,
      render: (text: any, record: any) => (
        <>
          {record.side === 'long' ? formatNum(record?.long_price) : formatNum(record?.short_price)}
        </>
      ),
    },
    {
      title: '平仓均价',
      dataIndex: 'pingCangJunJia',
      hideInSearch: true,
      render: (text: any, record: any) => (
        <>
          {record.side === 'long' ? formatNum(record?.short_price) : formatNum(record?.long_price)}
        </>
      ),
    },
    {
      title: '累计平仓量(USDT)',
      dataIndex: 'accum_size',
      hideInSearch: true,
      render: (text: any, record: any) => <div>{Math.abs(getUsdtNum(record, text))} USDT</div>,
    },
    {
      title: '最大持仓量(USDT)',
      dataIndex: 'max_size',
      hideInSearch: true,
      render: (text: any, record: any) => <div>{Math.abs(getUsdtNum(record, text))} USDT</div>,
    },
  ];

  // 员工列表
  const initYuanGong = async () => {
    const yuanGongs: any = await getYuanGong(userListApi);
    setYuanGongs(yuanGongs);
    setDefYuanGongId(setDefEmployeeId(yuanGongs));
  };

  return (
    <div className={`${styles.xxx} xxx`}>
      {isLocal() && <div>芝麻总盈亏：{zongYingKui}</div>}
      {yuanGongs && Object.keys(yuanGongs).length > 0 && (
        <ProTable
          rowKey="id"
          columns={columns}
          request={request}
          actionRef={tableRef}
          options={false}
          scroll={{ x: 1300 }}
          // pagination={false}
          loading={loading}
        />
      )}
    </div>
  );
}
